<template>
  <m-container class="add">
    <in-work-top-cell :info="{ ...$store.getters['inWork/getFormInfo'], status: showInBlankPallet ? 1 : 0 }">
      <view class="switch-button" v-if="showInBlankPallet">
        <m-switch :value="switchValue" @change="handleSwitchChange" />
        <text>空托盘入库</text>
      </view>
    </in-work-top-cell>

    <m-cell-group class="box" v-for="(item, index) in list" :key="index" weight="label">
      <m-cell :label="'库存' + (index + 1)" size="xs" :border="false">
        <template slot="link" v-if="list.length >= 2">
          <m-icon name="mask-close" size="25" @click="handleClickDelete(index)" />
        </template>
      </m-cell>
      <m-cell title="SKU名称" is-link @click="handleSelectSku(index)" :desc="item.skuName" size="xs"></m-cell>
      <m-cell-group class="box__inner" size="xs">
        <m-cell title="SKU编号">
          <view slot="center" class="center">{{ skuList.map[item.skuId] }} </view>
        </m-cell>
        <m-cell title="零件图号">
          <view slot="center" class="center">{{ item.skuPartNo }}</view>
        </m-cell>
        <m-cell title="毛重（kg）">
          <view slot="center" class="center"> {{ (item.grossWeight || 0) / 1000 }} </view>
        </m-cell>
      </m-cell-group>
      <m-cell title="仓库编号" is-link @click="handleSelectIms(index)" :desc="item.imsCode" size="xs"></m-cell>
      <m-cell-group class="box__inner" size="xs">
        <m-cell title="库位承重（kg）">
          <view slot="center" class="center"> {{ (item.unitWeight || 0) / 1000 }} </view>
        </m-cell>
        <m-cell title="价格范围（元）">
          <view slot="center" class="center" v-if="item.minPrice || item.maxPrice">
            <m-text filter="currency" :filter-text="(item.minPrice || 0) / 100"></m-text>-
            <m-text filter="currency" :filter-text="(item.maxPrice || 0) / 100"></m-text>
          </view>
        </m-cell>
      </m-cell-group>
      <m-cell title="打印条码" size="xs">
        <template slot="link">
          <m-radio-group inline v-model="item.needPrintBarcode">
            <m-radio :label="+item.value" v-for="(item, index) in options" :key="index" :disabled="getSwitch"
              >{{ item.label }}
            </m-radio>
          </m-radio-group>
        </template>
      </m-cell>
      <m-cell title="实际包装数量（个）" size="xs">
        <template slot="link">
          <u-number-box
            v-model="item.realPackageNumber"
            :min="1"
            :max="item.maxPackageNumber"
            :press-time="1500"
            :disabled="getSwitch"
          ></u-number-box>
        </template>
      </m-cell>
      <m-cell
        title="入库总数（包）"
        sub-title-color="#F34A33"
        :sub-title="item.maxPackageQuantity ? '最大数量为' + item.maxPackageQuantity + '个' : ''"
        size="xs"
      >
        <template slot="link">
          <u-number-box
            v-model="item.packageQuantity"
            :min="isNeed ? 2 : 1"
            :step="isNeed ? 2 : 1"
            :max="item.maxPackageQuantity"
            :press-time="1500"
            :disabled="getSwitch"
          ></u-number-box>
        </template>
      </m-cell>
    </m-cell-group>

    <view class="button" v-if="!switchValue">
      <m-button
        icon="plus"
        :icon-size="30"
        width="100%"
        background="transparent"
        type="primary"
        size="md"
        plain
        shape="round"
        :disabled="!!getDisabledSku"
        @click="handleClickAdd"
      >
        添加SKU
      </m-button>
    </view>

    <m-fixed>
      <view class="footer">
        <m-button width="26%" size="xl" type="default" plain @click="handleClickCancel">取消</m-button>
        <m-button width="70%" size="xl" @click="handleClickSave" :disabled="getDisabled" :loading="loading">
          保存
        </m-button>
      </view>
    </m-fixed>

    <in-work-select-dict-popup
      v-model="skuId"
      :visible.sync="visible"
      :title="list[currentIndex] ? list[currentIndex].skuName : '请选择SKU'"
      :options="getOptions"
      @confirm="handleConfirm"
    />

    <m-picker
      v-model="imsId"
      :visible.sync="visiblePicker"
      title="请选择仓库"
      :options="getImsOptions"
      poppable
      @confirm="handleImsCodeConfirm"
    />
  </m-container>
</template>

<script>
import { showModal } from '@/hooks'
import { router } from '@/router'
import { getDicts } from '@/api/modules/dict'
import { mapState } from 'vuex'
import {
  getSku,
  getIms,
  addWorkOrder,
  isNeedEvenNumberSku,
  existAreaOfSkuIds,
  skuList,
  listConfig,
} from '@/api/modules/in-work'
import deepClone from '@/utils/deep-clone'
import dayjs from 'dayjs'
import { useDoingInventory } from '@/hooks'

export default {
  data() {
    return {
      showInBlankPallet: false,
      switchValue: false,
      skuId: '',
      imsId: '',
      needPrintBarcode: 1,
      list: [
        {
          realPackageNumber: 0,
          packageQuantity: 1,
          needPrintBarcode: 0,
          skuId: undefined,
          imsId: null,
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      ],
      visible: false,
      visiblePicker: false,
      options: [],
      currentIndex: 0,
      isNeed: false,
      loading: false,
    }
  },
  computed: {
    ...mapState({
      form: (state) => state.inWork.form,
      imsList: (state) => state.cache.imsList,
      skuList: (state) => state.cache.skuList,
    }),
    getImsOptions() {
      const { imsIds } = this.list[this.currentIndex]
      return this.imsList.arr.filter((item) => (imsIds || '').split(',').includes(item.value + ''))
    },
    getDisabledSku() {
      let data = []
      const { imsId } = this.list[0]

      if (imsId) {
        data = this.skuList.arr.filter((item) => item.imsId.split(',').includes(imsId + ''))
      }
      return this.list.filter((item) => item.skuId === undefined).length || data.length === 0
    },
    getDisabled() {
      return !this.list.every((item) => item.skuId) || this.loading
    },
    getOptions() {
      let data = this.skuList.arr

      if (this.list.length > 1 && this.list[0].imsId) {
        const { imsId } = this.list[0]
        data = data.filter((item) => item.imsId.split(',').includes(imsId + ''))
      }

      return data
    },
    getSwitch() {
      return this.switchValue
    },
  },
  async onLoad() {
    await useDoingInventory('当前有正在执行的盘点计划单，入库单不会创建！')
    const { rows } = await listConfig({ configKey: 'isInBlankPallet' })
    if (rows.length) {
      this.showInBlankPallet = +rows[0].configValue
    }

    const { data } = await getDicts('barcode_yes_no')
    this.isNeed = await isNeedEvenNumberSku()
    this.options = data
  },
  methods: {
    handleSwitchChange() {
      if (!this.switchValue) {
        if (this.list.length > 1 || this.list[0].skuId) {
          showModal({
            title: '温馨提示',
            content: '开启后，将清空所有已添加的SKU，是否确认开启？',
            showCancelButton: true,
            slot: true,
            confirm: () => {
              this.confirm()
            },
          })
        }
        this.confirm()
      } else {
        this.switchValue = false
      }
    },
    async confirm() {
      const { rows } = await skuList({
        sku_code: 'WMS-P-',
      })
      if (rows.length === 0) {
        uni.showToast({
          title: '没有找到以WMS-P-开头的商品',
          icon: 'none',
        })
        return
      }

      this.list = [
        {
          realPackageNumber: 0,
          packageQuantity: 1,
          needPrintBarcode: 0,
          skuId: undefined,
          imsId: null,
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      ]

      this.switchValue = true
      this.handleConfirm(rows[0].skuId)
    },
    async handleImsCodeConfirm() {
      const imsId = +this.imsId
      await existAreaOfSkuIds({
        imsId,
        skuIds: this.list.map((item) => item.skuId).filter(Boolean),
      })

      this.list[this.currentIndex].imsId = imsId
      this.list[this.currentIndex].imsCode = this.imsList.map[imsId]
      this.currentIndex = 0
      this.list.forEach((item, index) => {
        if (item.imsId !== imsId) {
          this.list.splice(index, 1)
        }
      })
    },
    handleSelectIms(index) {
      showModal({
        title: '修改仓库提示',
        content: '请您确认是否要修改仓库？一旦修改后，非同仓库的SKU不支持选择，已添加过的非同仓库SKU系统也会自动删除。',
        showCancelButton: true,
        slot: true,
        confirm: () => {
          this.imsId = +this.list[index].imsId
          this.visiblePicker = true
          this.currentIndex = index
        },
      })
    },
    handleClickDelete(index) {
      showModal({
        title: '删除提示',
        content: '是否确认删除？',
        showCancelButton: true,
        slot: true,
        confirm: () => {
          this.list.splice(index, 1)
        },
      })
    },
    handleClickCancel() {
      router.back()
    },
    handleSelectSku(index) {
      if (this.getSwitch) {
        uni.showToast({
          title: '空托盘入库禁止选择SKU',
          icon: 'none',
        })
        return
      }
      this.currentIndex = index
      this.visible = true
    },
    async handleConfirm(val) {
      const {
        data: { packageNumber, partNo, imsId: imsIds, ...rest },
      } = await getSku(val)
      let { imsId } = this.list[0]
      if (imsId === null) {
        imsId = imsIds.split(',')[0]
      }

      const {
        data: { maxPrice, minPrice, unitWeight, imsCode },
      } = await getIms(imsId)

      const item = {
        ...(this.list[this.currentIndex] || {}),
        skuPartNo: partNo,
        ...rest,
        imsId,
        imsIds,
        maxPrice,
        minPrice,
        unitWeight,
        imsCode,
        maxPackageNumber: packageNumber,
        realPackageNumber: packageNumber,
        maxPackageQuantity: parseInt(unitWeight / (rest.grossWeight || 1)),
        remark: '',
      }

      await existAreaOfSkuIds({
        imsId,
        skuIds: [...this.list, item].map((item) => item.skuId).filter(Boolean),
      })

      this.$set(this.list, this.currentIndex, item)

      this.visible = false
    },
    handleClickAdd() {
      if (this.getTotalWeight()) {
        showModal({
          title: '超重提示',
          content: '所添加的仓库SKU已达到托盘最大承重范围了，无法在继续添加SKU了',
          confirmText: '我知道了',
        })
        return
      }

      const imsId = this.list[0].imsId
      this.list.push({
        realPackageNumber: 1,
        packageQuantity: 1,
        skuId: undefined,
        imsId,
        imsCode: this.imsList.map[imsId],
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
    },
    getTotalWeight() {
      const total = this.list.reduce((pre, curr) => {
        pre += curr.packageQuantity * curr.grossWeight
        return pre
      }, 0)

      const { unitWeight } = this.list[0]
      return unitWeight < total
    },
    async handleClickSave() {
      if (!this.list.length > 0) {
        uni.showToast({
          title: '至少添加一条入库单SKU',
          icon: 'none',
        })
        return
      }

      if (this.getTotalWeight()) {
        showModal({
          title: '超重提示',
          content: '所添加的仓库SKU已达到托盘最大承重范围了,请修改入库数量',
          confirmText: '我知道了',
        })
        return
      }

      this.loading = true
      showModal({
        title: '保存提示',
        content: '请问您选择确认是否需要保存添加这些仓库SKU,保存后将不能再修改。',
        confirmText: '保存',
        showCancelButton: true,
        confirm: async () => {
          const form = deepClone(this.form)
          form.status = 1
          form.totalQualityt = this.list.reduce((pre, curr) => pre + Number(curr.packageQuantity), 0)
          form.imsStockInOrderDetailList = this.list

          try {
            const { data } = await addWorkOrder(form)
            router.replace({
              name: 'InWorkDetail',
              params: {
                inOrderId: data,
                api: 'default',
                type: 'fastInWork',
              },
            })
          } catch (e) {}
          this.loading = false
        },
        cancel: () => {
          this.loading = false
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.add {
  .switch-button {
    font-size: 28rpx;
    color: #2c65a1;
  }
  .button {
    padding: 0 30rpx;
    margin-top: 10rpx;
    margin-bottom: 15rpx;
  }
  .box {
    &__inner {
      .center {
        color: #84898e;
      }
      ::v-deep {
        .cell {
          .badge {
            width: 200rpx;
          }
          &-group__wrap {
            margin: 0;
            background: #f4f8fc;
            border-radius: 0;
          }
          &:after {
            right: 0;
            left: 0;
          }
        }
      }
    }

    ::v-deep {
      .cell {
        &:after {
          border-color: #eaecee;
        }
      }
    }
  }

  .radio-group {
    width: auto;
    display: flex;
  }
  .footer {
    display: flex;
    justify-content: space-between;
  }
}
</style>
